<template>
    <el-button type="primary" @click="captureAndDownloadSnapshot">生成快照</el-button>
</template>

<script setup lang="ts">
import html2canvas from 'html2canvas';
const props = defineProps({
	targetModule:{
		type: Object as PropType<HTMLElement | null | undefined>,
		required: false,
	},
})
const captureAndDownloadSnapshot = async () => {
	try {
		const element = props.targetModule;
		if (!element) {
			throw new Error(`Element with id "${props.targetModule}" not found.`);
		}
		element.style.overflow = 'visible';
		// if(!props.isEcharts){
		// 	//克隆元素
		// 	const clone = element.cloneNode(true) as HTMLElement;
		// 	clone.style.overflow = 'visible'; // 确保克隆元素的滚动内容展开

		// 	//创建一个临时的容器来放置克隆元素
		// 	const tempContainer = document.createElement('div');
		// 	tempContainer.style.position = 'absolute';
		// 	tempContainer.style.top = '-9999px'; // 将克隆元素放置在屏幕外
		// 	tempContainer.style.left = '-9999px';
		// 	tempContainer.style.maxWidth = '10000px';
		// 	tempContainer.style.pointerEvents = 'none'; // 防止克隆元素干扰用户交互
		// 	tempContainer.appendChild(clone);

		// 	//将克隆元素添加到文档中
		// 	document.body.appendChild(tempContainer);
		// 	// 捕捉快照
		// 	const scale = window.devicePixelRatio || 1;
		// 	const canvas = await html2canvas(element, {
		// 		scale: scale,
		// 		useCORS: true,
		// 	});
		// 	document.body.removeChild(tempContainer);
		// 	const dataUrl = canvas.toDataURL('image/png');
		// 	downloadImage(dataUrl, 'snapshot.png');
		// }else{
		// 捕捉快照
		const scale = window.devicePixelRatio || 1;
		const canvas = await html2canvas(element, {
			scale: scale,
			useCORS: true,
		});
		const dataUrl = canvas.toDataURL('image/png');
		downloadImage(dataUrl, 'snapshot.png');
		// }
	} catch (error) {
		console.error('Error capturing snapshot:', error);
	}
};
const downloadImage = (dataUrl: string, filename: string) => {
	const link = document.createElement('a');
	link.href = dataUrl;
	link.download = filename;
	document.body.appendChild(link);
	link.click();
	document.body.removeChild(link);
};
</script>

<style scoped>
button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}
</style>